{-# LANGUAGE OverloadedStrings #-}

module Pages.DigestiveHelpers where

import Text.Digestive.Types (Form, mapView, (++>), (<++))
import Text.Digestive.Forms ()
import Text.Digestive.Common ()
import Text.Digestive.Forms.Html (FormHtml(..))
import Text.Digestive.Blaze.Html5 (BlazeFormHtml, label, errors)
import Text.Blaze.Html5 (Html)
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A

type BlazeForm m i a = Form m i Html BlazeFormHtml a

-- | maps a given function into a FormHtml data structure
modifyFormHtml :: (a -> b) -> FormHtml a -> FormHtml b
modifyFormHtml f FormHtml{formEncType, formHtml} = FormHtml{formEncType, formHtml = f . formHtml}

-- | Applies the given function to the HTML contents of the form
plug :: (Monad m, Functor m) => (v -> w) -> Form m i e (FormHtml v) a -> Form m i e (FormHtml w) a
plug = mapView . modifyFormHtml

tabularSection :: (Functor m, Monad m) => Html -> BlazeForm m i a -> BlazeForm m i a
tabularSection lbl = plug ((H.tr $ H.td H.! A.colspan "2" $ H.strong $ lbl) >>)

tabularInput :: (Monad m, Functor m) => String -> BlazeForm m i a -> BlazeForm m i a
tabularInput lbl form = plug H.tr $
                            plug H.th (label lbl) ++>
                            plug H.td form <++
                            errors

tabularForm :: (Monad m, Functor m) => BlazeForm m i a -> BlazeForm m i a
tabularForm = plug H.table
